import path from "path";
import multer from "multer";
import { UploadError } from "../../utils/errors";

// 存储目标
const imgTargetPath = path.resolve(__dirname, "../../../public/static/uploads");
const attachTargetPath = path.resolve(__dirname, "../../../public/static/attachment");

const imgExt = [".jpg", ".jpeg", ".png", ".gif", ".webp", ".bmp"];
const attachmentExt = [".xlsx", ".docx"];

// 定义存储文件名和路径
const storage = multer.diskStorage({
  destination: (_req, file, cb: any) => {
    if (imgExt.includes(path.extname(file.originalname))) {
      cb(null, imgTargetPath); // 使用定义好的路径
    } else {
      cb(null, attachTargetPath);
    }
  },
  filename: (_req, file: any, cb: any) => {
    // 使用时间戳作为文件名
    cb(null, Date.now() + path.extname(file.originalname));
  },
});

// 定义文件后缀白名单
const whiteList = [...imgExt, ...attachmentExt];
export const uploadMiddleware = multer({
  storage, // 应用定义好的存储方式
  fileFilter(_req, file: any, cb: any) {
    // 筛选出符合条件的文件
    if (whiteList.includes(path.extname(file.originalname))) {
      cb(null, true);
    } else {
      cb(new UploadError("文件格式不正确"));
    }
  },
  limits: {
    fileSize: 1024 * 1024 * 2, // 限制文件大小
    // fieldNameSize: 100
  },
});

export function getAccessPath(filename: string) {
  if (imgExt.includes(path.extname(filename))) {
    return `/static/uploads/${filename}`;
  }
  return `/static/attachment/${filename}`;
}
